using System;
using System.Collections.Generic;
using BuildMonitor.Properties;
using Microsoft.TeamFoundation.Build.Client;
using Amplify.Twitter;

namespace BuildMonitor.Engine
{
	public class TwitterBuildPublisherHelper
	{
		private readonly ILog log;
		private readonly BuildWatcher watcher;

		public TwitterBuildPublisherHelper(ILog log, BuildWatcher buildWatcher)
		{
			watcher = buildWatcher;
			watcher.BuildWatcherInitializing += Init;
			watcher.BuildCompletionEvent += BuildCompletionEvent;
			watcher.BuildQualityChangeEvent += BuildStatusChangeEvent;
			watcher.BuildWatcherStopping += Close;
			this.log = log;
		}

		private StatusClient client;

		public void Init(object sender, IEnumerable<BuildStoreEventArgs> events)
		{
			Twitter.SetCredentials(Settings.Default.TwitterAccount, Settings.Default.TwitterPassword);
			client = Twitter.CreateStatusClient();
		}

		public void BuildCompletionEvent(object sender, BuildStoreEventArgs buildStoreEvent)
		{
			log.Information("Build Completion Event");
			var status = buildStoreEvent.Data.Status;
			if (status.Equals(BuildStatus.Succeeded))
				client.Create("Yay! I got built successfully again!");
			if (status.Equals(BuildStatus.Failed))
				client.Create(string.Format("Oops!! {0} broke me. Go find them and beat them up!", buildStoreEvent.Data.RequestedBy));
			if (status.Equals(BuildStatus.PartiallySucceeded))
				client.Create(string.Format("Hmm... Something's not quite right.  Can you get {0} to have a look?", buildStoreEvent.Data.RequestedBy));
			if (status.Equals(BuildStatus.Stopped))
				client.Create(string.Format("I was building and then {0} asked me to stop.  Hmppf.", buildStoreEvent.Data.RequestedBy));
		}

		public void BuildStatusChangeEvent(object sender, BuildStoreEventArgs buildStoreEvent)
		{
			log.Information("Build Status Event");
			client.Create(String.Format("{0} changed my build quality to {1}", buildStoreEvent.Data.LastChangedBy, buildStoreEvent.Data.Quality));
		}

		public void Close(object sender, EventArgs e)
		{
			client.Create("I'm being turned off :-(");
		}
	}
}